package com.icangya.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icangya.DAO.*;
import com.icangya.Value.FootBall;
import com.icangya.Value.StaticValue;
import com.icangya.domain.*;
import com.icangya.service.IAdvertService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service("AdvertServiceImpl")
public class AdvertServiceImpl implements IAdvertService{

    @Autowired
    private IAdvertRecordDAO iAdvertRecordDAO;
    @Autowired
    private IAdvertClickDAO iAdvertClickDAO;
    @Autowired
    private IBalanceDAO iBalanceDAO;
    @Autowired
    private ICommissionFootDAO iCommissionFootDAO;
    @Autowired
    private IExpendRecordDAO iExpendRecordDAO;
    @Autowired
    private ICommissionRecordDAO iCommissionRecordDAO;
    @Autowired
    private IUserFootDAO iUserFootDAO;
    @Autowired
    private IGiftAdvertMoneyDAO iGiftAdvertMoneyDAO;
    @Autowired
    private IAdvertImageDAO iAdvertImageDAO;
    @Autowired
    private IFbFootGameDAO iFbFootGameDAO;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public AdvertRecord addAdvertRecord(AdvertRecord advertRecord, String[] fileUrl, int status) {

//        for(String key:fileUrl){
//            AdvertImage advertImage=new AdvertImage(1,key);
//            System.out.println(advertImage.getId()+"......................"+advertImage.getImgUrl());
//            //iAdvertImageDAO.save(advertImage);
//        }
        //status   0:游戏币  1：赠送广告金
        int result=0;
        AdvertRecord ar=new AdvertRecord();
        if(status==0) {
            advertRecord.setGiftAdvertMoney(0);
           result= iBalanceDAO.updateBanlanceByMoney(advertRecord.getOpenId(), -advertRecord.getAdvertTopMoney());
        }else if(status==1){
            advertRecord.setGiftAdvertMoney(1);
            //修改用户的赠送金额数量
           result= iGiftAdvertMoneyDAO.updateGiftAdvertMoney(advertRecord.getOpenId(),-advertRecord.getAdvertTopMoney());
        }

        if(result>0){
            //添加广告主的广告费支出记录
            iExpendRecordDAO.save(new ExpendRecord(advertRecord.getOpenId(), StaticValue.Advert, advertRecord.getAdvertTopMoney(), advertRecord.getCreateTime()));
          ar= iAdvertRecordDAO.get(iAdvertRecordDAO.save(advertRecord));
           for(String key:fileUrl){
               AdvertImage advertImage=new AdvertImage(ar.getId(),key);
               iAdvertImageDAO.save(advertImage);
           }

        }

        return ar;

    }



    @Override
    public Boolean checkAdvertMoney(String openId, double advertTopMoney,int status) {



        if(status==1){
            //判断用户是否还有赠送广告金的余额
            GiftAdvertMoney giftAdvertMoney= iGiftAdvertMoneyDAO.getGiftAdvertMoneyByOpenId(openId);
            double money=0.0;
            if(giftAdvertMoney!=null)
                money=giftAdvertMoney.getGitAdvertMoney();
            if(money<advertTopMoney)
                return false;
            return true;
        }


        //先获取用户详情
        Balance balance= iBalanceDAO.getBanlanceByOpenId(openId);
        if(balance!=null){
            if( balance.getMoney()>advertTopMoney)
                return true;
        }

        return false;
    }

    /**
     * 查询单条信息
     * @param id
     * @return
     */
    @Override
    public AdvertRecord getAdvertRecord(Long id) {
//        List<AdvertImage> imgList= iAdvertImageDAO.getAdvertImg(id);
//        JSONArray imgArray=new JSONArray();
//        if(imgList!=null){
//            for (AdvertImage advertImage: imgList) {
//                JSONObject object =new JSONObject();
//                object.put("imgUrl",advertImage.getImgUrl());
//                object.put("advertId",advertImage.getAdvertId());
//                imgArray.add(object);
//            }
//        }
//JSONObject jsonObject=new JSONObject();
//        jsonObject.put("advertImgUrl",imgArray);
////        jsonObject.put("advertRecord",)
        return iAdvertRecordDAO.getAdvertRecord(id);
//        return null;
    }


    /**
     * 删除单条广告记录
     * @param advertId
     * @return
     */
    @Override
    public Boolean deleteAdvertById(long advertId) {

       AdvertRecord advertRecord=  iAdvertRecordDAO.get(advertId);
       iAdvertRecordDAO.remove(advertRecord);
//        List<AdvertImage> imgList= iAdvertImageDAO.getAdvertImg(advertId);
         advertRecord=  iAdvertRecordDAO.get(advertId);
         if(advertRecord!=null)
             return false;
        return true;
    }



    @Override
    public AdvertClick addAdvertClick(AdvertClick advertClick) {

        //获取广告被点击的次数
        long count=iAdvertClickDAO.getCountAdvertClick(advertClick.getAdvertId());
        AdvertRecord advertRecord= iAdvertRecordDAO.getAdvertRecord(advertClick.getAdvertId());//获取用户该条广告费的上限

        if(advertRecord.getStatus()==1){
            return null;
        }
        //获取该广告被点击扣除的总费用
        double sumMoney=count*advertRecord.getAdvertMoney();
        if(advertRecord.getGiftAdvertMoney()==0){
            //判断广告的金额是否大于被用户点击的金额
            if(advertRecord.getAdvertTopMoney()-sumMoney>=advertRecord.getAdvertMoney()) {

                //设置用户获取的点击广告的金额，  //平台广告抽成 比率
                FbFootGame fbFootGame=  iFbFootGameDAO.getFbFootGameByType(0);
                if(fbFootGame!=null){
                    FootBall.advertRatio=fbFootGame.getProportion();
                    logger.info("bFootGame.getProportion()============================="+fbFootGame.getProportion());
                    logger.info("advertRatio============================="+FootBall.advertRatio);
                }

                double  bmoney=advertClick.getClickMoney()*(1-FootBall.advertRatio) ;
                if(bmoney<0){
                    return null;
                }
                logger.info("advertClick============================="+bmoney);
                BigDecimal big=new BigDecimal(bmoney);
                double money=big.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();//设置添加到数据库的金额只包含俩位小数
                advertClick.setClickMoney(money);

                //添加用户获得点击广告佣金的记录
                iCommissionRecordDAO.save(new CommissionRecord(advertClick.getOpenId(), StaticValue.AdvertClick,money,advertClick.getClickTime()));
                Commission commission= iCommissionFootDAO.selectUserCommis(advertClick.getOpenId());
                money= commission.getMoney()+money;
                //将用户获得的点击广告金存入佣金
                int result=iCommissionFootDAO.changeMoney(advertClick.getOpenId(),money);

               AdvertClick advertClick1= iAdvertClickDAO.get(iAdvertClickDAO.save(advertClick));//存储广告被点击的记录

                    if(result>0){
                        count=iAdvertClickDAO.getCountAdvertClick(advertClick.getAdvertId());

                            advertRecord.setShamPageView(advertRecord.getShamPageView()+1);
                            advertRecord.setRealPageView(advertRecord.getRealPageView()+1);
                            iAdvertRecordDAO.update(advertRecord);

                        //获取该广告被点击时的被扣除的总费用
                        double sum2Money=count*advertRecord.getAdvertMoney();
                        if(advertRecord.getAdvertTopMoney()-sum2Money<advertRecord.getAdvertMoney()){
                            //修改该条广告的状态为 1，广告费不足
                            iAdvertRecordDAO.updateAdvertByStatus(advertClick.getAdvertId());
                        }
                        logger.warn("修改佣金记录成功，修改金额为 == " + advertClick.getClickMoney() + "|修改时间是 == " +advertClick.getClickTime());
                    }
                //返回广告被点击的记录
                return  advertClick1;
            }else{
                //广告费不足   修改该条广告的状态为 1，
                iAdvertRecordDAO.updateAdvertByStatus(advertClick.getAdvertId());
            }


        }else if(advertRecord.getGiftAdvertMoney()==1 ){
            // sumMoney=count*advertRecord.getAdvertMoney();
            if(advertRecord.getAdvertTopMoney()-sumMoney<advertRecord.getAdvertMoney())
                iAdvertRecordDAO.updateAdvertByStatus(advertClick.getAdvertId()); //广告费不足   修改该条广告的状态为 1，

            //点击广告时广告金是官方赠送的，不返现到佣金， 添加广告点击记录，但是用户不会获得佣金
            //存储广告被点击的记录
                advertClick.setClickMoney(0);
               iAdvertClickDAO.get(iAdvertClickDAO.save(advertClick));

                advertRecord.setShamPageView(advertRecord.getShamPageView()+1);
                advertRecord.setRealPageView(advertRecord.getRealPageView()+1);
                iAdvertRecordDAO.update(advertRecord);

               count=iAdvertClickDAO.getCountAdvertClick(advertClick.getAdvertId());
               sumMoney=count*advertRecord.getAdvertMoney();
            if(advertRecord.getAdvertTopMoney()-sumMoney<advertRecord.getAdvertMoney())
                iAdvertRecordDAO.updateAdvertByStatus(advertClick.getAdvertId()); //广告费不足   修改该条广告的状态为 1，

            return null;
        }

        return null;


    }

 // 获取用户未点击的广告
    @Override
    public JSONObject getAdvertNotClick(String openId, int startPage) {
        List list =  iAdvertRecordDAO.getAdvertNotClick(openId,startPage);
        if(list==null)
            return null;

        JSONArray jsonArray=new JSONArray();
        if(startPage > (int)list.get(1)){
            return null;
        }
        for (AdvertRecord adv:(List<AdvertRecord>)list.get(0)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", adv.getId());
            jsonObject.put("advertContent", adv.getAdvertContent());
            List<AdvertImage> imgList = iAdvertImageDAO.getAdvertImg(adv.getId());
            JSONArray imgArray = imgJSONArray(imgList);
            jsonObject.put("advertImgUrl", imgArray);
            jsonObject.put("advertMoney", adv.getAdvertMoney());
            jsonObject.put("advertTopMoney", adv.getAdvertTopMoney());
            jsonObject.put("createTime", adv.getCreateTime());
            jsonObject.put("modifiedTime", adv.getModifiedTime());
            jsonObject.put("openId", adv.getOpenId());
            jsonObject.put("status", adv.getStatus());

            Object[] obj = iUserFootDAO.getNickName(adv.getOpenId());

            if (obj == null) {
                continue;
            }

            logger.info("广告编号......................"+adv.getId());

            jsonObject.put("nickName",obj[0]);//获得用户昵称
            jsonObject.put("headImgurl",obj[1]);//用户头像
            jsonObject.put("openId",adv.getOpenId());
//           jsonObject.put("advertClick",iAdvertClickDAO.getCountAdvertClick(adv.getId()));//广告被浏览的次数
            jsonObject.put("advertClick",adv.getShamPageView());//广告被浏览的次数
            jsonObject.put("gitMoney",adv.getGiftAdvertMoney());  //广告金官方赠送  1
            jsonArray.add(jsonObject);
        }
        JSONObject jsonObject1=new JSONObject();
        jsonObject1.put("advertStatus",0);   // 0 是下一页有数据   1是没有数据
        if(startPage+ 1> (int)list.get(1)){
            jsonObject1.put("advertStatus",1);   // 0 是下一页有数据   1是没有数据
        }
        jsonObject1.put("value",jsonArray);
        jsonObject1.put("totalPage",list.get(1));
        jsonObject1.put("inPage",list.get(2));

        return  jsonObject1;
        }

    @Override
    public List getAdvertRecordShame() {
        return iAdvertRecordDAO.getAdvertRecordShame();
    }

    @Override
    public int updateAdvertShampageview(long id, long ramd) {
        return iAdvertRecordDAO.updateAdvertShampageview(id,ramd);
    }

    @Override
    public JSONObject getAdvert(int startPage,int advertRow){

        List list = iAdvertRecordDAO.getAdvertAll(startPage,advertRow);
        JSONArray jsonArray=new JSONArray();

        if(list==null)
            return null;
        if(startPage > (int)list.get(1)){
            return null;
        }
        for (AdvertRecord adv:(List<AdvertRecord>)list.get(0)) {
//            System.out.print("广告内容："+adv.getAdvertContent());

            JSONObject jsonObject=new JSONObject();
            jsonObject.put("id",adv.getId());
            jsonObject.put("advertContent",adv.getAdvertContent());
            List<AdvertImage> imgList= iAdvertImageDAO.getAdvertImg(adv.getId());
            JSONArray imgArray= imgJSONArray(imgList);

            jsonObject.put("advertImgUrl",imgArray);
            jsonObject.put("advertMoney",adv.getAdvertMoney());
            jsonObject.put("advertTopMoney",adv.getAdvertTopMoney());
            jsonObject.put("createTime",adv.getCreateTime());
            jsonObject.put("modifiedTime",adv.getModifiedTime());
            jsonObject.put("openId",adv.getOpenId());
            jsonObject.put("status",adv.getStatus());
            Object[] obj = iUserFootDAO.getNickName(adv.getOpenId());

            if (obj == null) {
                continue;
            }
            logger.info("广告编号......................"+adv.getId());

            jsonObject.put("nickName",obj[0]);//获得用户昵称
            jsonObject.put("headImgurl",obj[1]);//用户头像
            jsonObject.put("openId",adv.getOpenId());
//            long count=iAdvertClickDAO.getCountAdvertClick(adv.getId());
//            jsonObject.put("advertClick",count);//广告被浏览的次数
            jsonObject.put("advertClick",adv.getShamPageView());//广告被浏览的次数
            jsonObject.put("gitMoney",0);
            //广告金官方赠送  1
            if(adv.getGiftAdvertMoney()==1)
                jsonObject.put("gitMoney",1);

            jsonArray.add(jsonObject);

        }


        JSONObject jsonObject1=new JSONObject();
        jsonObject1.put("value",jsonArray);
        jsonObject1.put("totalPage",list.get(1));
        jsonObject1.put("inPage",list.get(2));

        return jsonObject1;
    }



    /**
     * 查询单个用户发布的所有广告信息
     */

    @Override
    public JSONObject getAdvertAll(String openId) {
        List list;
        list= iAdvertRecordDAO.getAdvertRecord(openId);
        JSONArray jsonArray=new JSONArray();
        if(list==null)
            return null;
        for (AdvertRecord adv:(List<AdvertRecord>)list) {

            JSONObject jsonObject=new JSONObject();
                jsonObject.put("id",adv.getId());
                jsonObject.put("advertContent",adv.getAdvertContent());
            List<AdvertImage> imgList= iAdvertImageDAO.getAdvertImg(adv.getId());
            JSONArray imgArray= imgJSONArray(imgList);
                jsonObject.put("advertImgUrl",imgArray);
                jsonObject.put("advertMoney",adv.getAdvertMoney());
                jsonObject.put("advertTopMoney",adv.getAdvertTopMoney());
                jsonObject.put("createTime",adv.getCreateTime());
                jsonObject.put("modifiedTime",adv.getModifiedTime());
                logger.info(adv.getCreateTime()+"发布广告的时间");
                jsonObject.put("openId",adv.getOpenId());
                jsonObject.put("status",adv.getStatus());
            jsonObject.put("gitMoney",adv.getGiftAdvertMoney());
            jsonObject.put("advertClick",adv.getShamPageView());//广告被浏览的次数
//                jsonObject.put("advertClick",iAdvertClickDAO.getCountAdvertClick(adv.getId()));//广告被浏览的次数
            jsonArray.add(jsonObject);

        }

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("value",jsonArray);

        return jsonObject;
    }

    @Override
    public JSONObject getAdvertById(Long advertId) {
        JSONObject jsonObject=new JSONObject();
        AdvertRecord advertRecord= iAdvertRecordDAO.getAdvertRecord(advertId);
        if(advertRecord==null)
            return null;
        jsonObject.put("advertId",advertRecord.getId());
        jsonObject.put("advertContent",advertRecord.getAdvertContent());
        List<AdvertImage> imgList= iAdvertImageDAO.getAdvertImg(advertRecord.getId());

        JSONArray imgArray= imgJSONArray(imgList);

        jsonObject.put("advertImgUrl",imgArray);
        Object[] obj = iUserFootDAO.getNickName(advertRecord.getOpenId());
        if(obj!=null){
            jsonObject.put("nickName",obj[0]);//获得用户昵称
            jsonObject.put("headImgurl",obj[1]);//用户头像
        }
        jsonObject.put("openId",advertRecord.getOpenId());
//        User user=iUserFootDAO.selectUserByOpenId(advertRecord.getOpenId());
//        if(user!=null){
//            jsonObject.put("nickName",user.getNickName());//获得用户昵称
//            jsonObject.put("headImgurl",user.getHeadImgUrl());//用户头像
//        }

        return jsonObject;
    }

    public JSONArray imgJSONArray(List<AdvertImage> imgList ){
        JSONArray imgArray=new JSONArray();
        if(imgList!=null){
            for (AdvertImage advertImage: imgList) {
                JSONObject object =new JSONObject();
                object.put("imgUrl",advertImage.getImgUrl());
                object.put("advertId",advertImage.getAdvertId());
                imgArray.add(object);
            }
        }
        return imgArray;
    }
    @Override
    public Boolean updateAdvertMoney(long uid, double money) {

        boolean bool=false;
        //修改广告金额的的时候先获取该条广告的信息
      AdvertRecord advertRecord=  iAdvertRecordDAO.getAdvertRecord(uid);

        if(money<advertRecord.getAdvertMoney())
            return bool;
        if(advertRecord.getGiftAdvertMoney()==0) {
                Balance balance = iBalanceDAO.getBanlanceByOpenId(advertRecord.getOpenId());
                if (balance.getMoney() > money) {//用户的广告金余额要大于该条广告的增加费用
                    int result = iAdvertRecordDAO.updateAdvertTopMoney(uid, money);
                    if (result > 0) {//修改广告金额成功， 添加用户的支出记录，修改用户广告金
                        int res = iBalanceDAO.updateBanlanceByMoney(advertRecord.getOpenId(), -money);//修改用户余额
                        iExpendRecordDAO.save(new ExpendRecord(advertRecord.getOpenId(), StaticValue.Advert, money, advertRecord.getCreateTime()));//添加用户支出记录
                        bool = true;
                    }

                }
        }else if(advertRecord.getGiftAdvertMoney()==1){
          GiftAdvertMoney giftAdvertMoney=  iGiftAdvertMoneyDAO.getGiftAdvertMoneyByOpenId(advertRecord.getOpenId());
          if(giftAdvertMoney.getGitAdvertMoney()>money){//赠送广告金余额要大于修改的金额
              int result = iAdvertRecordDAO.updateAdvertTopMoney(uid, money);
              if (result > 0) {//修改广告金额成功， 添加用户的支出记录，修改用户广告金
                  iGiftAdvertMoneyDAO.updateGiftAdvertMoney(advertRecord.getOpenId(), -money);
                  iExpendRecordDAO.save(new ExpendRecord(advertRecord.getOpenId(), StaticValue.Advert, money, advertRecord.getCreateTime()));//添加用户支出记录
                  bool = true;
              }
          }
        }

        return bool;
    }



    @Override
    public boolean checkAdvertByOpenId(String openId, Long advertId) {

        return iAdvertClickDAO.getAdvertClickByOpenId(openId,advertId);
    }


}







